<?php

//include_once APPLICATION_DIR . "/library/external/PEAR/Validate/Validate.php";
include_once APPLICATION_DIR . "/application/model/LOGIN.php";
//
class Login extends DataObjects_LOGIN {
	function Login() {

	}
	/**
	 * Enter description here...
	 *
	 * @deprecated version 0.0.0 - Sep 11, 2007
	 *
	 * @param unknown_type $id
	 * @return unknown
	 */
	function getFromId($id) {
		$this->ID = $id;
		$this->whereAdd("DISABLED != 1");
		$this->find();
		return $this->fetch();

	}

	/**
	 * Update new SALT_VALUE for REGIE
	 */
	public function updateNewSaltValue()
	{
		srand((double)microtime() * 1000000);
		$this->SALT_VALUE = substr(md5(rand(0, 32000)), 0, 20);
		$this->update();
	}

	/**
	 * Get login information by ID, don't care about DISABLED
	 * @param int $id login_id
	 * @return
	 */
	function getFromIdIgnoreDisabled($login_id) {
		$this->selectAdd("EMAIL, PASS");
		$this->ID = $login_id;
		$this->find();
		return $this->fetch();
	}

	/**
	 * Get list of Login for the specific Annonceur
	 *
	 * @param int $annonceur_id
	 * @param string $nom
	 */
	function findAnnonceurLoginListe($annonceur_id,$nom="") {
		$this->whereAdd("ID_ANNONCEUR = '" . $annonceur_id . "'");
		$this->whereAdd("DISABLED != '1'");
		if ($nom!="")
			$this->whereAdd("PRENOM LIKE '%".mysql_real_escape_string($nom)."%'
							 OR NOM LIKE '%".mysql_real_escape_string($nom)."%'
								");
		$this->orderBy('PRENOM, NOM');
		$this->find();

	}

	/**
	 * Get the specific login for the specific annonceur
	 *
	 * @param int $login_id
	 * @param int $annonceur_id
	 */
	function getFromAnnonceurId($login_id, $annonceur_id) {
		$this->ID_ANNONCEUR = $annonceur_id;
		$this->ID = $login_id;
		$this->find();
		$this->fetch();

	}

	//crud process
	/**
	 * Enter description here...
	 *
	 * @deprecated version 0.0.0 - Sep 11, 2007
	 *
	 * @return unknown
	 */
	function isValid() {

		global $act; //

		if ($act == "valid_creer" || $act == "valid_modifier") {
			if (empty ($this->EMAIL)) {
				$this->report = _LB_EMAIL_IS_EMPTY;
				return false;
			}
			if (strlen($this->EMAIL) > 255) {
				$this->report = _LB_EMAIL_IS_TOO_LONG;
				return false;

			}
			if (!checkEmailValide($this->EMAIL)) {
				$this->report = _LB_INVALID_EMAIL;
				return false;

			}
			if (!empty ($this->NOM) && strlen($this->NOM) > 100) {
				$this->report = _LB_NAME_IS_TOO_LONG;
				return false;

			}
			if (!empty ($this->PRENOM) && strlen($this->PRENOM) > 100) {
				$this->report = _LB_PRENOM_IS_TOO_LONG;
				return false;

			}
			if (!empty ($this->FONCTION) && strlen($this->FONCTION) > 255) {
				$this->report = _LB_FONCTION_IS_TOO_LONG;
				return false;

			}
			if (isset ($_SESSION["is_update"]) && $_SESSION["is_update"] == TRUE) {
				if (empty ($this->NOM)) {
					$this->report = _LB_NAME_IS_EMPTY;
					return false;

				}
				if (empty ($this->PRENOM)) {
					$this->report = _LB_PRENOM_IS_EMPTY;
					return false;

				}
				if (empty ($this->FONCTION)) {
					$this->report = _LB_FONCTION_IS_EMPTY;
					return false;

				}

			}

			if ($act == "valid_creer") {
				if (empty ($_POST['login_PASS']) || empty ($_POST['login_PASS_CONFIRM'])) {
					$this->report = _LB_PASSWORD_IS_EMPTY;
					return false;

				} else {
					if (strlen($_POST['login_PASS']) > 20 || strlen($_POST['login_PASS_CONFIRM']) > 20) {
						$this->report = _LB_PASSWORD_IS_TOO_LONG;
						return false;

					}
					if (isset ($_POST['login_PASS']) && isset ($_POST['login_PASS_CONFIRM']) && $_POST['login_PASS'] != $_POST['login_PASS_CONFIRM']) {
						$this->report = _LB_PASSWORD_DOESNT_MATCH;
						return false;

					}

				}

			}

		}
		return true;

	}

	/**
	 * Check if email of the user exist
	 *
	 * @param string $email
	 * @return int $id is the Login ID
	 */
	function userExistByEmail($email) {

		$t = new Login();
		$t->EMAIL = $email;
		$t->DISABLED=0;
		$t->find(1);
		return $t->ID;
	}

	/**
	 * Check if CODE of the user exist
	 *
	 * @param string $code
	 * @param string $loginID
	 * @return int $id is the Login ID
	 */
	function codeExistByLoginID($code, $loginID) {
		$t = new Login();
		$t->CODE = $code;
		if (trim($loginID) != '' && $loginID != 0)
		{
			$t->whereAdd("ID <> " . $loginID);
		}
		$t->DISABLED=0;
		$t->find(1);
		return $t->ID;
	}

	/**
	 * Check if EMAIL of the user exist
	 *
	 * @param string $email
	 * @param string $loginID
	 * @return int $id is the Login ID
	 */
	function emailExistByLoginID($email, $loginID) {
		$t = new Login();
		$t->EMAIL = $email;
		if (trim($loginID) != '' && $loginID != 0)
		{
			$t->whereAdd("ID <> " . $loginID);
		}
		$t->DISABLED=0;
		$t->find(1);
		return $t->ID;
	}

	/**
	 * Insert/Update the Login
	 *
	 * @return data_object updated
	 */
	function store() {
		if ($this->ID==0)
			return $this->insert();
		else return $this->update();
	}

	/**
	 * Update the Login's Disabled = 1 on Login deletion
	 *
	 * @return data_object updated
	 */
	function supprimer() {
		//disable login/agent
		$this->DISABLED = 1;
		//$this->ID = $login_id;
		if ($this->update() === FALSE) {
			$this->report = _LB_CANNOT_DELETE_IN_DB;
			return false;

		} else {
			return true;

		}

	}

	/**
	 * Update Date Last Login to current date if user login to the system
	 *
	 * @return data_object updated
	 */
	function updateLogin() {
		$this->DATE_LAST_LOGIN = date("Y-m-d G:i:s");
		$this->update();
	}

	/**
	 * update ID_LOGIN_MASTER of the ANNONCEUR when inserting or deleting a LOGIN
	 *
	 * @return data_object updated

	function updateLoginMaster() {
		if ($this->ID_ANNONCEUR != "" && $this->ID_ANNONCEUR != 0) {
			$annonceur = new Annonceur();
			$annonceur->get($this->ID_ANNONCEUR);

			if ($annonceur->ID_LOGIN_MASTER==0)
			{
				$annonceur->ID_LOGIN_MASTER = $this->ID;
				$annonceur->update();
			}

			$login = new Login();
			if ($login->get($annonceur->ID_LOGIN_MASTER) == 0 || $login->DISABLED) {
				$login = new Login();
				$login->DISABLED = 0;
				$login->ID_ANNONCEUR = $annonceur->ID;
				$login->orderBy("NOM, PRENOM");
				$login->find();
				$login->fetch();
				$annonceur->ID_LOGIN_MASTER = $login->ID;
				$annonceur->update();
			}

		}

	}*/
	/**
	 * Check if Login is a annonceur
	 *
	 * @return boolean true if Login is a annonceur
	 */
	function isAnnonceur() {
		return !$this->isRegie() && !$this->isAgent();

	}

	/**
	 * Check if Login is a regie
	 *
	 * @return boolean true if Login is a annonceur
	 */
	function isRegie() {
		return isset ($this->IS_REGIE) && $this->IS_REGIE;

	}

	/**
	 * Check if Login is a Regie
	 *
	 * @return boolean true if Login is a Regie
	 */
	function isRegieAccount() {
		return ( ($this->isRegie()) && ($this->IS_REGIE == 1));
	}

	/**
	 * Check if Login is a Support
	 *
	 * @return boolean true if Login is a Support
	 */
	function isSupport() {
		return ( ($this->isRegie()) && ($this->IS_REGIE == 2));
	}

	/**
	 * Check if Login is a agent
	 *
	 * @return boolean true if Login is a annonceur
	 */
	function isAgent() {
		return isset ($this->IS_AGENT) && $this->IS_AGENT;
	}

	function changePassword() {

		$password = randomCode(8);
		$this->PASS = sha1($password);
		$this->ACTIVATION_CODE = "";

		return $this->update();
	}

	function isAllowedAccessProject($project = USER_PROJECT_ACCESS_ALLOWED_VODAFONELIVE) {

		if ( (!$this->IS_REGIE) && !ALLOW_ANNONCEUR )
			return false;

		if ( ($this->IS_REGIE == ADMIN_HTC) && !ALLOW_REGIE )
			return false;

		//$annonceur = new Annonceur();
		if ($this->ID_ANNONCEUR==0)
			return TRUE;

		//if (!$annonceur->get($this->ID_ANNONCEUR))
			//return FALSE;

		switch ($project) {
			case USER_PROJECT_ACCESS_ALLOWED_VODAFONELIVE :
				return $annonceur->ALLOWED_VL == 1;
			case USER_PROJECT_ACCESS_ALLOWED_GALLERY :
				return $annonceur->ALLOWED_GALLERY == 1;
			case USER_PROJECT_ACCESS_ALLOWED_FAST :
				return $annonceur->ALLOWED_FAST == 1;

		}

		return FALSE;
	}

	/**
	 * Check if Login can be deleted
	 *
	 * @return boolean $count is true if $count > 1; false otherwise
	 */
	function canDelete()
	{
		$login = new Login();

		/*
		if($this->IS_REGIE > 0)
			$login->IS_REGIE = $this->IS_REGIE;
		else
			$login->ID_ANNONCEUR = $this->ID_ANNONCEUR;
		*/

		if($this->ID == $_SESSION['userID'])
			$login->whereAdd('ID = ' . $_SESSION['userID']);

		$login->whereAdd('DISABLED = 0');

		return ($login->count() > 1);
	}

	/**
	 * Check whether or not account with specific ID login is exist
	 *
	 * @return boolean true if exist, otherwise false
	 */
	function isExistLoginID()
	{
		$login = new Login();
		$login->whereAdd('ID = ' . $_SESSION['userID']);
		$login->whereAdd('DISABLED = 0');
		if ($login->count() > 0)
		{
			return true;
		}
		else
		{
			return false;
		}
	}

	/**
	 * Disable login account of an Annonceur of Mandataire
	 *
	 * @param int $id_annonceur : ID of Annonceur or Mandataire
	 */
	function disableAccountOfOwner($id_annonceur)
	{
		$sql = "UPDATE LOGIN
				SET DISABLED = 1
				WHERE ID_ANNONCEUR = ".$id_annonceur;

		$this->query($sql);
	}

	/**
	 * when a user tries to login with the wrong password, increment LOGIN_ATTEMPTS
	 * if a user tries to login and LOGIN_ATTEMPTS > ALLOWED_LOGIN_ATTEMPTS, set DEACTIVATED = 1
	 *
	 * @param <string> $login
	 */
	function increaseLoginAttempts($login)
	{
		if ($login)
		{
			$obj_login = new Login();
			$obj_login->EMAIL = mysql_real_escape_string($login);
			$obj_login->find();

			if ($obj_login->fetch())
			{
				$obj_login->LOGIN_ATTEMPTS += 1;

				if ($obj_login->LOGIN_ATTEMPTS >= ALLOWED_LOGIN_ATTEMPTS)
				{
					$obj_login->DEACTIVATED = 1;
				}

				$obj_login->update();
			}
		}
	}

	/**
	 * check if user login is deactivated or not
	 * @param <string> $login
	 * @return <boolean> true if deactivated
	 */
	function isDeactivated($login)
	{
		$bln_ok = false;

		if ($login)
		{
			$obj_login = new Login();
			$obj_login->EMAIL = mysql_real_escape_string($login);
			$obj_login->find();
			if ($obj_login->fetch())
			{
				if ($obj_login->DEACTIVATED)
				{
					$bln_ok = true;
				}
			}
		}

		return $bln_ok;
	}

	/**
	 * when a user login with the right password and if LOGIN_ATTEMPTS <= ALLOWED_LOGIN_ATTEMPTS, then set LOGIN_ATTEMPTS = 0
	 * @param <string> $login
	 */
	function resetLoginAttempts($login)
	{
		if ($login)
		{
			$obj_login = new Login();
			$obj_login->EMAIL = mysql_real_escape_string($login);
			$obj_login->find();
			if ($obj_login->fetch())
			{
				if (!$obj_login->DEACTIVATED)
				{
					$obj_login->LOGIN_ATTEMPTS = 0;
					$obj_login->update();
				}
			}
		}
	}

	/**
	 * Rule applys in transform progress
	 *
	 * @param unknown_type $new_login
	 * @return unknown
	 */
	public static function isPassTransformRule($new_login)
	{
		$bln_pass = true;

		// if transform-to account is SUPPORT or REGIE
		if ($new_login->IS_REGIE)
		{
			if ($_SESSION["is_regie"] == ADMIN_HTC
				|| ($_SESSION["is_regie"] == ADMIN_SUPPORT && $new_login->IS_REGIE == ADMIN_SUPPORT))
			{
				$bln_pass = false;
			}
		}
		return $bln_pass;
	}

    function getUserQuery($nom = '')
    {
        // get list of regie or support from LOGIN table
        $sql = " SELECT LOGIN.ID, LOGIN.NOM, NULL AS TELEPHONE, ".
            " IF(LOGIN.IS_REGIE = " . ADMIN_HTC . ", " . ACCOUNT_TYPE_REGIE . ", " . ACCOUNT_TYPE_SUPPORT . ") USER_TYPE, " .
            " LOGIN.PRENOM, LOGIN.DATE_LAST_LOGIN, LOGIN.EMAIL, LOGIN.PASS, " .
            " NULL AS ID_AGENT, LOGIN.IS_REGIE " .
            " FROM LOGIN " .
            " WHERE LOGIN.DISABLED = 0
                AND LOGIN.IS_REGIE = 2 ";
        if ($nom!='')
            $sql .= " AND (LOGIN.PRENOM LIKE '%".mysql_real_escape_string($nom)."%' OR LOGIN.NOM LIKE '%".mysql_real_escape_string($nom)."%')";

        $order_query = " ORDER BY NOM";

        return $sql . $order_query;
    }

}